﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RolesController.cs" company="Dongacs">
//   2011
// </copyright>
// <summary>
//   Defines the RolesController type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QLPKWeb.BussinessDelegate.PhanQuyen;
using QLPKWeb.Controllers.Base;
using QLPKWeb.Models.FormBean.PhanQuyen;
using DONGACS.Common;
using DONGACS.DTO;
using Webdiyer.WebControls.Mvc;

namespace QLPKWeb.Controllers
{
    public class RolesController : BaseController
    {
        RolesServiceDelegate RolesServiceDelegate = new RolesServiceDelegate();
        UsersServiceDelegate UsersServiceDelegate = new UsersServiceDelegate();
        //
        // GET: /Roles/
        public ActionResult List(int? id)
        {
            RolesForm form = new RolesForm();

            BuildRolesList(form);
            form.ID = -1; //Dấu hiệu nhận biết tạo mới userd
            form.IsEnable = true;
            //form.CreateDateString = DateTime.Now.ToString("dd/MM/yyyy");
            //form.UpdateDateString = DateTime.Now.ToString("dd/MM/yyyy");
            form.CreateDate = DateTime.Now;
            form.UpdateDate = DateTime.Now;

            if (Convert.ToInt32(Session["USERID"]) != 0)
            {
                var userLogin = UsersServiceDelegate.GetUsersById(Convert.ToString(Session["USERID"]));
                form.CreateByUser = form.UpdateByUser = userLogin.LastName + " " + userLogin.FirstName;
            }
            else
            {
                form.CreateByUser = form.UpdateByUser = string.Empty;
            }

            //Phân trang
            form.RolesPagedList = new PagedList<RolesDto>(form.RolesList, id ?? 1, CommonVariables.PaggedItemsPerPage);

            return View("Index", form);
        }


        //public ActionResult Create(int? id)
        //{
        //    RolesForm form = new RolesForm();

        //    BuildRolesList(form);
        //    form.ID = -1; //Dấu hiệu nhận biết tạo mới userd
        //    form.IsEnable = true;
        //    form.CreateDate = DateTime.Now;
        //    form.UpdateDate = DateTime.Now;
        //    form.CreateByUser = SessionDetail.USERNAME;
        //    form.UpdateByUser = SessionDetail.USERNAME;

        //    //Phân trang
        //    form.RolesPagedList = new PagedList<RolesDto>(form.RolesList, id ?? 1, 5);

        //    return View("Index", form);
        //}

        [AcceptVerbs(HttpVerbs.Get)]
        [ValidateInput(false)]
        public ActionResult Create(int? id) //id : page number
        {
            return Redirect("~/Roles/List/" + id);
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(RolesForm form)
        {
            var newRoles = new RolesDto();

            //Lấy thông tin Role mới từ Form
            newRoles = RolesServiceDelegate.BuildNewRoles(form);

            //Lưu user mới xuống database
            bool isCreateRoles = RolesServiceDelegate.AddNewRoles(newRoles);

            form.MessageCreateRoles = isCreateRoles ? "Tạo Role thành công !" : "Tạo Role thất bại, xin thử lại !";

            //Refesh danh sách Role
            BuildRolesList(form);
            //Refesh form
            if (Convert.ToInt32(Session["USERID"]) != 0)
            {
                var userLogin = UsersServiceDelegate.GetUsersById(Convert.ToString(Session["USERID"]));
                form.CreateByUser = form.UpdateByUser = userLogin.LastName + " " + userLogin.FirstName;
            }
            else
            {
                form.CreateByUser = form.UpdateByUser = string.Empty;
            }


            //Get Id của user mới Save
            form.ID = RolesServiceDelegate.GetRolesByName(newRoles.RoleName).ID;

            //Phân trang
            int id = 1;
            form.RolesPagedList = new PagedList<RolesDto>(form.RolesList, id, 5);

            return View("Index", form);
        }


        [AcceptVerbs(HttpVerbs.Get)]
        [ValidateInput(false)]
        public ActionResult Edit(int? id) //id : page number
        {
            return Redirect("~/Roles/List/" + id);
        }

        //Cập nhật thông tin một Role
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult Edit(RolesForm form)
        {
            RolesDto editRoles = new RolesDto();

            //Lấy thông tin role mới từ Form
            editRoles = RolesServiceDelegate.BuildEditRoles(form);

            //Get Id của role hiện hành(edit)
            //editRoles.ID = RolesServiceDelegate.GetRolesByName(form.RoleName).ID;
            editRoles.ID = Convert.ToInt32(form.ID);


            //Lưu Roles mới xuống database

            bool isUpdateRoles = this.RolesServiceDelegate.Update(editRoles);

            form.MessageEditRoles = isUpdateRoles ? "Cập nhật Role thành công !" : "Cập nhật Role thất bại, xin thử lại !";

            //Refesh danh sách roles
            BuildRolesList(form);

            //Refesh form
            if (Convert.ToInt32(Session["USERID"]) != 0)
            {
                var userLogin = UsersServiceDelegate.GetUsersById(Convert.ToString(Session["USERID"]));
                form.CreateByUser = form.UpdateByUser = userLogin.LastName + " " + userLogin.FirstName;
            }
            else
            {
                form.CreateByUser = form.UpdateByUser = string.Empty;
            }

            form.ID = editRoles.ID;

            //Phân trang
            int id = 1;
            form.RolesPagedList = new PagedList<RolesDto>(form.RolesList, id, 5);

            return View("Index", form);
        }


        public ActionResult Delete(string roleID)
        {
            RolesServiceDelegate.ShiftDelete(roleID);
            return RedirectToAction("List");
        }


        //kiểm tra role đã tồn tại chưa
        public JsonResult IsExistRole(string RoleName)
        {
            var rolesDto = this.RolesServiceDelegate.GetRolesByName(RoleName);

            bool isExistRole = rolesDto != null ? true : false;

            return this.Json(isExistRole, JsonRequestBehavior.AllowGet);
        }

        //Kiểm tra xem Role có đang được gán cho User nào đó hay chưa
        public JsonResult CheckRolesIsUsedAjax(string roleID)
        {
           bool data = RolesServiceDelegate.GetUsersInRolesByRoleId(roleID).Count != 0 ? true : false;

            return this.Json(data, JsonRequestBehavior.AllowGet);
        }

        //lấy thông tin Roles gán cho Json phục vụ chức năng Edit Roles
        public JsonResult RolesEditAjax(string id)
        {
            var dto = this.RolesServiceDelegate.GetRolesByID(id);
            
            var userCreate = UsersServiceDelegate.GetUsersById(Convert.ToString(dto.CreateBy));
            var userUpdate = UsersServiceDelegate.GetUsersById(Convert.ToString(dto.UpdateBy)); 

            dto.CreateByUser = dto.CreateBy != 0 && userCreate != null ? userCreate.LastName + " " + userCreate.FirstName : string.Empty;
            dto.UpdateByUser = dto.UpdateBy != 0 && userUpdate != null ? userUpdate.LastName + " " + userUpdate.FirstName : string.Empty;
            dto.CreateDateString = dto.CreateDate.ToString("dd/MM/yyyy");
            dto.UpdateDateString = dto.UpdateDate.ToString("dd/MM/yyyy");
            return this.Json(dto, JsonRequestBehavior.AllowGet);
        }

        public JsonResult RolesNewAjax()
        {
            var userLogin = UsersServiceDelegate.GetUsersById(Session["USERID"].ToString());
            var newObj = new object[2] { userLogin != null ? userLogin.LastName + " " + userLogin.FirstName : string.Empty, DateTime.Now };

            return this.Json(newObj, JsonRequestBehavior.AllowGet);
        }


        private void BuildRolesList(RolesForm form)
        {
            //Lấy danh sách user không bị đánh dấu IsDelete = 1
            form.RolesList = RolesServiceDelegate.GetAllRoles();

            // adding more sothing.....

            foreach (var rolesDto in form.RolesList)
            {   //lấy tên ngừoi tạo hay thay đổi thông tin Roles
                
                var userUpdate = UsersServiceDelegate.GetUsersById(Convert.ToString(rolesDto.UpdateBy));
                var userCreate = UsersServiceDelegate.GetUsersById(Convert.ToString(rolesDto.CreateBy));
                rolesDto.IsUsed = RolesServiceDelegate.GetUsersInRolesByRoleId(Convert.ToString(rolesDto.ID)).Count != 0 ? true : false;
                rolesDto.HavePermission = RolesServiceDelegate.GetRolesInPathsByRolesId(Convert.ToString(rolesDto.ID)).Count != 0 ? true : false;
                rolesDto.UpdateByUser = rolesDto.UpdateBy != 0 && userUpdate != null ? userUpdate.LastName + " " + userUpdate.FirstName : string.Empty;
                rolesDto.CreateByUser = rolesDto.CreateBy != 0 && userCreate != null ? userCreate.LastName + " " + userCreate.FirstName : string.Empty;
            }   
        }
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ManageRolesWithPermissions(int? id)
        {
            var form = new RolesForm();
            
            BuildRolesList(form);

            //Phân trang
            form.RolesPagedList = new PagedList<RolesDto>(form.RolesList, id ?? 1, CommonVariables.PaggedItemsPerPage);
            //lấy giá trị trang hiện hành
            form.CurrentPageNumber = id ?? 1;

            ////Get all Paths in database
            form.PathsList = new List<PathsDto>();
            form.PathsList = this.RolesServiceDelegate.GetPaths();

            ////Get all RolesInPaths by RolesId RolesInPaths Table
            form.RolesInPathsByRolesIdList = new List<RolesInPathsDto>();
            form.PathsForRolesList = new List<PathsDto>();
            if (form.RolesList.Count != 0)
            {
                form.CurrentRolesId = form.RolesPagedList[0].ID.ToString();

                form.RolesInPathsByRolesIdList = this.RolesServiceDelegate.GetRolesInPathsByRolesId(form.CurrentRolesId);

                ////Build all Paths for 1 specifiable Roles from  RolesInPaths table:
                for (int i = 0; i < form.RolesInPathsByRolesIdList.Count; i++)
                {
                    for (int j = 0; j < form.PathsList.Count; j++)
                    {
                        if (form.RolesInPathsByRolesIdList[i].PathId == form.PathsList[j].ID)
                        {
                            form.PathsForRolesList.Add(form.PathsList[j]);
                        }
                    }
                }
            }

            ////Get all Blocks in Application base on Paths table
            IList<object> blocksList = new List<object>();
            blocksList = this.UsersServiceDelegate.GetAllBlocksInPaths();
            form.Blocks = new List<string>();
            foreach (var block in blocksList)
            {
                form.Blocks.Add((string)block);
            }

            //Get all Module By block in Application base on Paths table
            form.ModulesByBlockArray = new IList<string>[form.Blocks.Count];
            int t = 0;
            foreach (string block in form.Blocks)
            {

                IList<object> moduleListByBlockTemp = UsersServiceDelegate.GetAllModulesInPathsByBlocks(block); // lấy các Module theo Block

                IList<string> moduleListByBlock = new List<string>();

                foreach (var module in moduleListByBlockTemp)// chuyen list<object> sang list<string>
                {
                    moduleListByBlock.Add((string)module);
                }

                form.ModulesByBlockArray[t++] = moduleListByBlock;
            }

            ////Get all Module in Application base on Paths table : cũ Version 1
            //IList<object> modules = new List<object>();
            //modules = this.UsersServiceDelegate.GetAllModuleInPaths();
            //form.Modules = new List<string>();
            //foreach (var module in modules)
            //{
            //    form.Modules.Add((string)module);
            //}

            return View("ManageRolesWithPermissions", form);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        [ValidateInput(false)]
        public ActionResult ManageRolesWithPermissionsUpdate(int? id)//id : page number
        {
            return Redirect("~/Roles/ManageRolesWithPermissions/" + id);
        }
        
        /// <summary>
        /// Manages the roles with pages.
        /// </summary>
        /// <param name="form">The form to post.</param>
        /// <returns>A ActionResult</returns>
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ManageRolesWithPermissionsUpdate(RolesForm form)
        {
            //form.RolesNameSearch = HttpUtility.HtmlEncode(form.RolesNameSearch.Trim());
            //var dictionaryPaging = new Dictionary<string, object> { { "IsDelete", 0 } };
            // dictionaryPaging.Add("RoleName", form.RolesNameSearch);

            //var dictionary = new Dictionary<string, object> { { "IsDelete", false } };

            ////Process paging for Roles List
            ////by default : page = 1
            //int pageNo = 1;
            //if (!Equals(form.PageNumber, 0))
            //{
            //    pageNo = form.PageNumber;
            //}

            //var pagedRolesDto = new PagedResult<RolesDto>();

            //pagedRolesDto = this.RolesServiceDelegate.ListRoles(
            //                                                    dictionaryPaging,
            //                                                    (pageNo - 1) * CommonVariables.PaggedItemsPerPage,
            //                                                    CommonVariables.PaggedItemsPerPage);
            //form.RolesList = pagedRolesDto.Entities;

            //IPagination<RolesDto> custPage = new CustomPagination<RolesDto>(
            //                                                    pagedRolesDto.Entities,
            //                                                    pageNo,
            //                                                    CommonVariables.PaggedItemsPerPage,
            //                                                    Convert.ToInt32(pagedRolesDto.TotalCount));

            //form.CustPage = custPage;
            //form.PageNumber = pageNo;
            
            if (form.UpdateFlag)
            {
                try
                {
                    IList<RolesInPathsDto> dtos = new List<RolesInPathsDto>();
                    string[] newRolesInPathsString = !string.IsNullOrEmpty(form.NewRolesInPathsString) ? form.NewRolesInPathsString.Split('|') : new string[0]; //// list of PathId

                    //IList<string> pathIdsToUpdate = new List<string>();

                    for (int i = 1; i < newRolesInPathsString.Length; i++)
                    {
                        if (!String.IsNullOrEmpty(newRolesInPathsString[i]))
                        {
                            string[] modulePermissions = newRolesInPathsString[i].Split('-');
                            //// query all Paths that has permissiontype and module as modulePermissions
                            if (modulePermissions.Length == 2 && !String.IsNullOrEmpty(modulePermissions[0]) && !String.IsNullOrEmpty(modulePermissions[1]))
                            {
                                string module = modulePermissions[0].Trim();
                                string permissionType = modulePermissions[1].Trim();
                                IList<PathsDto> pathsDtos =
                                    this.RolesServiceDelegate.GetAllPathsByModulesAndPermissionType(module,
                                                                                                    permissionType);
                                foreach (PathsDto dto in pathsDtos)
                                {
                                    var rolesInPathsDto = new RolesInPathsDto();
                                    rolesInPathsDto.RoleId = Convert.ToInt32(form.CurrentRolesId);
                                    rolesInPathsDto.PathId = Convert.ToInt32(dto.ID);
                                    rolesInPathsDto.IsEnable = 1;
                                    rolesInPathsDto.IsDelete = 0;
                                    rolesInPathsDto.CreateDate = DateTime.Now;
                                    rolesInPathsDto.UpdateDate = DateTime.Now;
                                    rolesInPathsDto.Createby = Convert.ToInt32(Session["USERID"]);
                                    rolesInPathsDto.UpdateBy = Convert.ToInt32(Session["USERID"]);

                                    dtos.Add(rolesInPathsDto);
                                }
                            }
                        }
                    }

                    this.RolesServiceDelegate.UpdateManageRolesWithPermissions(dtos, form.CurrentRolesId);

                    form.UpdateSatusMessage = "Cập nhật thành công !";

                    //// reGet all RolesInPaths by current RolesId at RolesInPaths Table
                    //form.RolesInPathsByRolesIdList = this.RolesServiceDelegate.GetRolesInPathsByRolesId(form.CurrentRolesId);

                    ////reBuild all Paths for 1 specifiable Roles from  RolesInPaths table:
                    //form.PathsForRolesList = new List<PathsDto>();
                    //for (int i = 0; i < form.RolesInPathsByRolesIdList.Count; i++)
                    //{
                    //    for (int j = 0; j < form.PathsList.Count; j++)
                    //    {
                    //        if (form.RolesInPathsByRolesIdList[i].PathId == form.PathsList[j].ID)
                    //        {
                    //            form.PathsForRolesList.Add(form.PathsList[j]);
                    //        }
                    //    }
                    //}

                    //return View("ManageRolesWithPermissions", form);
                }
                catch (Exception)
                {
                    form.UpdateSatusMessage = "Cập nhật thất bại, xin thử lại !";
                    ////return RedirectToAction("ManageRolesWithPages", form);
                    //return View("ManageRolesWithPermissions", form);
                }
            }

            //Me
            BuildRolesList(form);

            //Phân trang
            form.RolesPagedList = new PagedList<RolesDto>(form.RolesList, form.CurrentPageNumber, CommonVariables.PaggedItemsPerPage);
            //


            ////Get all Paths in database
            form.PathsList = new List<PathsDto>();
            form.PathsList = this.RolesServiceDelegate.GetPaths();

            ////Get all RolesInPaths by RolesId RolesInPaths Table
            form.RolesInPathsByRolesIdList = new List<RolesInPathsDto>();

            ////form.RolesInPathsByRolesIdList = this.RolesServiceDelegate.RolesInPathsService.GetRolesInPathsByRolesId(rolesDtos[0].ID.ToString());
            //if ((form.SearchOrPagingClickFlag || form.SearchFlag) && (form.RolesList.Count != 0))
            //{
            //    form.CurrentRolesId = form.RolesList[0].ID.ToString();
            //}

            if (form.RolesClickFlag || form.UpdateFlag)
            {
                form.CurrentRolesId = form.CurrentRolesIdTemp;
            }

            form.RolesInPathsByRolesIdList = this.RolesServiceDelegate.GetRolesInPathsByRolesId(form.CurrentRolesId);

            ////Get all Blocks in Application base on Paths table
            IList<object> blocksList = new List<object>();
            blocksList = this.UsersServiceDelegate.GetAllBlocksInPaths();
            form.Blocks = new List<string>();
            foreach (var block in blocksList)
            {
                form.Blocks.Add((string)block);
            }

            //Get all Module By block in Application base on Paths table
            form.ModulesByBlockArray = new IList<string>[form.Blocks.Count];
            int t = 0;
            foreach (string block in form.Blocks)
            {

                IList<object> moduleListByBlockTemp = UsersServiceDelegate.GetAllModulesInPathsByBlocks(block); // lấy các Module theo Block

                IList<string> moduleListByBlock = new List<string>();

                foreach (var module in moduleListByBlockTemp)// chuyen list<object> sang list<string>
                {
                    moduleListByBlock.Add((string)module);
                }

                form.ModulesByBlockArray[t++] = moduleListByBlock;
            }

            ////Get all Module in Application base on Paths table : bản cũ : version 1
            //IList<object> modules = new List<object>();
            //modules = this.UsersServiceDelegate.GetAllModuleInPaths();
            //form.Modules = new List<string>();
            //foreach (var module in modules)
            //{
            //    form.Modules.Add((string)module);
            //}

            ////Build all Paths for 1 specifiable Roles from  RolesInPaths table:
            form.PathsForRolesList = new List<PathsDto>();
            for (int i = 0; i < form.RolesInPathsByRolesIdList.Count; i++)
            {
                for (int j = 0; j < form.PathsList.Count; j++)
                {
                    if (form.RolesInPathsByRolesIdList[i].PathId == form.PathsList[j].ID)
                    {
                        form.PathsForRolesList.Add(form.PathsList[j]);
                    }
                }
            }

            return View("ManageRolesWithPermissions", form);

        }
    }
}
